# @Time : 2020/7/31 11:20
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np

"""
cv.approxPolyDP() 用来构造指定精度的逼近多边形曲线.该函数的语法格式为:
approxCurve = cv.approxPolyDP(curve,epsilon,closed)
返回值是逼近多边形的点集.
curve: 轮廓
epsilon: 精度,原始轮廓的边界点与逼近多边形边界之间的最大距离.
closed: 布尔类型.该值为True时,逼近多边形是封闭的;否则,逼近多边形是不封闭的.

函数cv.approxPolyDP() 采用的是Douglas-Peucker算法(DP算法).
该算法首先从轮廓中找到距离最远的两个点,并将两点相连.接下来,在轮廓上找到一个离当前直线最远的点,并将该点与原有的直线连成一个
封闭的多边形,此时得到一个三角形.将上述过程不断迭代,将新找到的距离当前多边形最远的点加入到结果中.当轮廓上所有的点到当前多边形的距离
都小于函数cv.approxPolyDP()的参数epsilon的值时,就停止迭代.
epsilon是逼近多边形的精度信息,通常情况下,将该精度设置为多边形总长度的百分比形式.
"""
img = cv.imread("cc.bmp")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

T, thres = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
cv.imshow("Thres", thres)
image, contours, hierarchy = cv.findContours(thres, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

adp = img.copy()
epsilon = 0.2 * cv.arcLength(contours[0],True)
approx = cv.approxPolyDP(contours[0],epsilon,True)
cv.drawContours(adp,[approx],-1,(0,255,0),1)
cv.imshow("Approx_0.2",adp)

adp = img.copy()
epsilon = 0.1 * cv.arcLength(contours[0],True)
approx = cv.approxPolyDP(contours[0],epsilon,True)
cv.drawContours(adp,[approx],-1,(0,255,0),1)
cv.imshow("Approx_0.1",adp)

adp = img.copy()
epsilon = 0.05 * cv.arcLength(contours[0],True)
approx = cv.approxPolyDP(contours[0],epsilon,True)
cv.drawContours(adp,[approx],-1,(0,255,0),1)
cv.imshow("Approx_0.05",adp)


adp = img.copy()
epsilon = 0.01 * cv.arcLength(contours[0],True)
approx = cv.approxPolyDP(contours[0],epsilon,True)
cv.drawContours(adp,[approx],-1,(0,255,0),1)
cv.imshow("Approx_0.01",adp)



cv.waitKey(0)
cv.destroyAllWindows()

















